package com.lagou.edu.service.impl;

import com.lagou.edu.dao.CodeDao;
import com.lagou.edu.pojo.Code;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.service.EmailFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Random;

@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private CodeDao codeDao;



    @Override
    public String createCode(String email) {
        Code code = null;
        Code byEmail = codeDao.findByEmail(email);
        if(null == byEmail){
            code = new Code();
            code.setId(Long.parseLong(new Random().nextInt()+""));
        }else {
            code = byEmail;
        }
        Random random = new Random();
        String codeStr = random.nextInt(10000) + "";
        code.setEmail(email);
        code.setCode(codeStr);
        code.setCreateTime(new Timestamp(System.currentTimeMillis()));
        code.setExpireTime(new Timestamp(code.getCreateTime().getTime() + 600000));
        codeDao.save(code);
        return codeStr;
    }

    @Override
    public String validateCode(String code) {
        Code byCode = codeDao.findByCode(code);
        if(null != byCode){
            if((System.currentTimeMillis() - byCode.getCreateTime().getTime()) > 60 * 10 * 1000){
                return "验证码已过期，请重新获取";
            }
        }else {
            return "验证码不存在";
        }
        return "yes";
    }

}
